document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('searchInput');
    const engineSelect = document.getElementById('engineSelect');

    const engines = {
        bing: q => `https://www.bing.com/search?q=${encodeURIComponent(q)}`,
        google: q => `https://www.google.com/search?q=${encodeURIComponent(q)}`,
        baidu: q => `https://www.baidu.com/s?wd=${encodeURIComponent(q)}`
    };

    // 读取本地保存的搜索引擎
    const savedEngine = localStorage.getItem('selectedEngine');
    if (savedEngine && engines[savedEngine]) {
        engineSelect.value = savedEngine;
    }

    // 监听选择变化并保存
    engineSelect.addEventListener('change', () => {
        localStorage.setItem('selectedEngine', engineSelect.value);
    });

    const performSearch = () => {
        const query = searchInput.value.trim();
        const engine = engineSelect.value;
        if (query) {
            window.location.href = engines[engine](query);
        }
    };

    searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            performSearch();
        }
    });

    // 异步获取一言
    async function fetchQuote() {
        try {
            const res = await fetch('https://international.v1.hitokoto.cn/?encode=json');
            const data = await res.json();
            if (data && data.hitokoto) {
                document.getElementById('quote').textContent = data.hitokoto + (data.from_who && data.from_who.trim() ? " ---- " + data.from_who : "");
            }
        } catch (e) {
            document.getElementById('quote').textContent = '获取失败';
            console.error('获取一言失败:', e);
        }
    }
    fetchQuote();

    // 更新时间
    function updateTime() {
        const now = new Date();
        const timeStr = now.toLocaleString();
        document.getElementById('currentTime').textContent = timeStr;
    }
    updateTime();
    setInterval(updateTime, 1000);

    // 收藏网站功能
    const favoritesContainer = document.getElementById('favorites');
    const addFavoriteBtn = document.getElementById('addFavoriteBtn');
    const favoriteModal = document.getElementById('favoriteModal');
    const saveFavButton = document.getElementById('saveFavButton');
    const cancelFavButton = document.getElementById('cancelFavButton');
    const favNameInput = document.getElementById('favName');
    const favUrlInput = document.getElementById('favUrl');

    // 编辑收藏相关
    const favoriteEditModal = document.getElementById('favoriteEditModal');
    const editFavNameInput = document.getElementById('editFavName');
    const editFavUrlInput = document.getElementById('editFavUrl');
    const updateFavButton = document.getElementById('updateFavButton');
    const deleteFavButton = document.getElementById('deleteFavButton');
    const cancelEditFavButton = document.getElementById('cancelEditFavButton');

    // 当前正在编辑的收藏索引
    let currentEditIndex = -1;

    // 从 localStorage 加载自定义收藏列表
    let customFavorites = JSON.parse(localStorage.getItem('customFavorites')) || [];
    function renderCustomFavorites() {
        // 移除之前渲染的自定义收藏（通过 class="custom" 标识）
        const existing = document.querySelectorAll('.favorite.custom');
        existing.forEach(el => el.remove());
        // 在“+”按钮之前插入，每个附加一个编辑按钮
        customFavorites.forEach((fav, index) => {
            const a = document.createElement('a');
            a.href = fav.url;
            a.className = 'favorite custom';
            a.target = '_blank';
            const iconDiv = document.createElement('div');
            iconDiv.className = 'icon';
            // 显示名称首字母
            iconDiv.textContent = fav.name.charAt(0).toUpperCase();
            const nameDiv = document.createElement('div');
            nameDiv.className = 'name';
            nameDiv.textContent = fav.name;
            a.appendChild(iconDiv);
            a.appendChild(nameDiv);

            // 创建编辑按钮
            const editBtn = document.createElement('div');
            editBtn.className = 'edit-btn';
            editBtn.textContent = '编辑';
            // 绑定点击事件打开编辑弹出层
            editBtn.addEventListener('click', (e) => {
                e.preventDefault();
                currentEditIndex = index;
                editFavNameInput.value = fav.name;
                editFavUrlInput.value = fav.url;
                favoriteEditModal.style.display = 'flex';
            });
            a.appendChild(editBtn);
            // 插入到“+”按钮之前
            favoritesContainer.insertBefore(a, addFavoriteBtn);
        });
    }
    renderCustomFavorites();

    // “添加”弹出层显示
    addFavoriteBtn.addEventListener('click', (e) => {
        e.preventDefault();
        favNameInput.value = '';
        favUrlInput.value = '';
        favoriteModal.style.display = 'flex';
    });
    // 取消添加
    cancelFavButton.addEventListener('click', () => {
        favoriteModal.style.display = 'none';
    });
    // 保存新的收藏，自动检查网址前缀
    saveFavButton.addEventListener('click', () => {
        let name = favNameInput.value.trim();
        let url = favUrlInput.value.trim();
        if (!name || !url) {
            alert('请输入收藏名称和网址！');
            return;
        }
        // 如果网址不以 http:// 或 https:// 开头，则添加 https://
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
            url = 'https://' + url;
        }
        customFavorites.push({ name, url });
        localStorage.setItem('customFavorites', JSON.stringify(customFavorites));
        renderCustomFavorites();
        favoriteModal.style.display = 'none';
    });

    // 取消编辑
    cancelEditFavButton.addEventListener('click', () => {
        favoriteEditModal.style.display = 'none';
    });
    // 更新收藏
    updateFavButton.addEventListener('click', () => {
        let name = editFavNameInput.value.trim();
        let url = editFavUrlInput.value.trim();
        if (!name || !url) {
            alert('请输入收藏名称和网址！');
            return;
        }
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
            url = 'https://' + url;
        }
        if (currentEditIndex > -1) {
            customFavorites[currentEditIndex] = { name, url };
            localStorage.setItem('customFavorites', JSON.stringify(customFavorites));
            renderCustomFavorites();
        }
        favoriteEditModal.style.display = 'none';
    });
    // 删除收藏
    deleteFavButton.addEventListener('click', () => {
        if (currentEditIndex > -1) {
            // 确认删除
            if (confirm('确定删除此收藏吗？')) {
                customFavorites.splice(currentEditIndex, 1);
                localStorage.setItem('customFavorites', JSON.stringify(customFavorites));
                renderCustomFavorites();
                favoriteEditModal.style.display = 'none';
            }
        }
    });

    // 泡泡背景趣味效果
    function createBubbles() {
        const bubbleBg = document.getElementById('bubbleBg');
        if (!bubbleBg) return;
        const bubbleCount = 24;
        const bubbles = [];
        function randomBetween(a, b) { return Math.random() * (b - a) + a; }
        function spawnBubble() {
            const bubble = document.createElement('div');
            bubble.className = 'bubble';
            const size = randomBetween(24, 72);
            bubble.style.width = size + 'px';
            bubble.style.height = size + 'px';
            // 初始参数
            const params = {
                x0: randomBetween(0, window.innerWidth),
                y0: randomBetween(window.innerHeight * 0.5, window.innerHeight),
                amplitude: randomBetween(40, 120), // 左右摆幅
                freq: randomBetween(0.5, 1.2), // 摆动频率
                speed: randomBetween(18, 32), // 上升速度（越小越慢）
                phase: randomBetween(0, Math.PI * 2),
                size,
                opacity: randomBetween(0.3, 0.7),
                alive: true
            };
            bubble.style.opacity = params.opacity;
            bubble.style.left = params.x0 + 'px';
            bubble.style.top = params.y0 + 'px';
            bubble.style.pointerEvents = 'auto';
            bubble._bubbleParams = params;
            bubble.addEventListener('click', function(e) {
                e.stopPropagation();
                this.classList.add('pop');
                createBubbleBurst(this);
                params.alive = false;
                setTimeout(() => {
                    this.remove();
                    spawnBubble();
                }, 600);
            });
            bubbles.push(bubble);
            bubbleBg.appendChild(bubble);
        }
        for (let i = 0; i < bubbleCount; i++) {
            spawnBubble();
        }
        // 动画主循环
        function animateBubbles() {
            const now = Date.now() / 1000;
            for (let i = 0; i < bubbles.length; i++) {
                const bubble = bubbles[i];
                if (!bubble._bubbleParams || !bubble._bubbleParams.alive) continue;
                const p = bubble._bubbleParams;
                // y随时间上升，x为正弦曲线
                const t = now * p.freq + p.phase;
                const x = p.x0 + Math.sin(t) * p.amplitude;
                p.y0 -= 0.5 * (60 / p.speed); // 上升速度
                // 超出顶部则重生
                if (p.y0 + p.size < -20) {
                    p.x0 = randomBetween(0, window.innerWidth);
                    p.y0 = window.innerHeight + p.size;
                    p.amplitude = randomBetween(40, 120);
                    p.freq = randomBetween(0.5, 1.2);
                    p.speed = randomBetween(18, 32);
                    p.phase = randomBetween(0, Math.PI * 2);
                }
                bubble.style.left = x + 'px';
                bubble.style.top = p.y0 + 'px';
            }
            requestAnimationFrame(animateBubbles);
        }
        animateBubbles();
        // 泡泡爆裂碎片动画
        function createBubbleBurst(bubble) {
            const rect = bubble.getBoundingClientRect();
            const parentRect = bubbleBg.getBoundingClientRect();
            const cx = rect.left + rect.width/2 - parentRect.left;
            const cy = rect.top + rect.height/2 - parentRect.top;
            const count = Math.floor(randomBetween(8, 14));
            for (let i = 0; i < count; i++) {
                const frag = document.createElement('div');
                frag.className = 'bubble-frag';
                const angle = (2 * Math.PI / count) * i + randomBetween(-0.2, 0.2);
                const dist = randomBetween(30, 60);
                const x = Math.cos(angle) * dist;
                const y = Math.sin(angle) * dist;
                frag.style.left = cx + 'px';
                frag.style.top = cy + 'px';
                frag.style.setProperty('--frag-x', x + 'px');
                frag.style.setProperty('--frag-y', y + 'px');
                frag.style.background = 'radial-gradient(circle, #fff 40%, #00bfff 80%, #ff69b4 100%)';
                bubbleBg.appendChild(frag);
                setTimeout(() => frag.remove(), 700);
            }
        }
    }
    createBubbles();
});